﻿
using System;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Best.SmartCms.Config;
using Best.SmartCms.Domain.Security;
using Best.SmartCms.Dto.Common;
using Best.SmartCms.Dto.Enums;
using Best.SmartCms.Service.Common;
using Microsoft.IdentityModel.Tokens;

namespace Best.SmartCms.Service.Security
{
    /// <summary>
    /// Token 相关操作
    /// </summary>
    public class LoginTokenService : IService
    {
        private const string TokenRedisKey = "LoginToken_{0}_{1}";

        /// <summary>
        /// 生成签名
        /// </summary>
        /// <param name="user"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public string CreateToken(User user, RequestSourceEnum source)
        {
            var token = Guid.NewGuid().ToString();
            var days = ConfigurationManagerEx.AppSettings["Auth:JwtExpireDays"];
            var expires = DateTime.UtcNow.AddDays(Convert.ToDouble(days));
            SaveToken(user.Phone, token);
            return CreateToken(user, token, source, expires);
        }

        private string CreateToken(User user, string token, RequestSourceEnum source, DateTime expires)
        {
            var claims = new[]
            {
                new Claim(Claims.Uid, user.Id.ToString()),
                new Claim(Claims.Phone, user.Phone ?? ""),
                new Claim(Claims.Token, token),
                new Claim(Claims.Source, ((int) source).ToString())
            };

            var key = ConfigurationManagerEx.AppSettings["Auth:JwtKey"];
            var issuer = ConfigurationManagerEx.AppSettings["Auth:JwtIssuer"];
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var jwtSecurityToken = new JwtSecurityToken
            (
                issuer,
                issuer,
                claims,
                expires: expires,
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
            );

            return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="keyCode"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool VerifyToken(string keyCode, string token)
        {
            return true;
            //var redisToken = FindToken(keyCode);
            //if (string.IsNullOrEmpty(redisToken))
            //{
            //    return false;
            //}

            //return token == redisToken;
        }

        private string FindToken(string keyCode)
        {

            //var key = string.Format(TokenRedisKey, SystemCode, keyCode);
            //var token = RedisService.GetValue(key);
            //return string.IsNullOrEmpty(token) ? null : token;

            return null;
        }

        /// <summary>
        /// 保存token到redis 默认两天
        /// </summary>
        /// <param name="keyCode"></param>
        /// <param name="token"></param>
        private void SaveToken(string keyCode, string token)
        {
            //var key = string.Format(TokenRedisKey, SystemCode, keyCode);
            //RedisService.SetValue(key, token, new TimeSpan(30, 0, 0, 0));
        }

    }
}